<?php

namespace app\common\lib;

class Arr {

    /**
     * @param $data
     * 分类树，支持无限极分类
     * @return array
     */
    public static function getTree($data) {
        $items = [];
        foreach ($data as $v) {
            $items[$v['category_id']] = $v;
        }
        $tree = [];
        foreach ($items as $id => $item) {
            if (isset($items[$item['pid']])) {
                $items[$item['pid']]['list'][] = &$items[$id];
            } else {
                $tree[] = &$items[$id];
            }
        }
        return $tree;
    }

    /**
     * 三级分类截取各级个数
     * @param $data
     * @param int $firstCount
     * @param int $secondCount
     * @param int $threeCount
     * @return array
     */
    public static function sliceTreeArr($data, $firstCount = 5, $secondCount = 4, $threeCount = 3) {
        $data = array_slice($data, 0, $firstCount);
        foreach ($data as $k => $v) {
            if (!empty($v['list'])) {
                $data[$k]['list'] = array_slice($v['list'], 0, $secondCount);
                if ($k > $secondCount) {
                    break;
                }
                foreach ($v['list'] as $kk => $vv) {
                    if (!empty($vv['list'])) {
                        $data[$k]['list'][$kk]['list'] = array_slice($vv['list'], 0, $threeCount);
                    }
                }
            }
        }
        return $data;
    }

    /**
     * 分页默认返回的数据
     * @param $num
     * @return array
     */
    public static function getPaginateDefaultData($num) {
        return [
            'total'        => 0,
            'per_page'     => $num,
            'current_page' => 1,
            'last_page'    => 0,
            'data'         => [],
        ];
    }

    public static function defaultSearch() {
        return [
            'name'      => '一级分类',
            //分类的定位焦点 ，注意这个地方 有可能是一个，有可能是两个，也有可能没有
            'focus_ids' => [1, 11],
            'list'      => [
                [
                    ['id' => 1, 'name' => '二级分类1'],
                    ['id' => 2, 'name' => '二级分类2'],
                    ['id' => 3, 'name' => '二级分类3'],
                    ['id' => 4, 'name' => '二级分类4'],
                    ['id' => 5, 'name' => '二级分类5'],
                ],
                [
                    ['id' => 11, 'name' => '三级分类1'],
                    ['id' => 12, 'name' => '三级分类2'],
                    ['id' => 13, 'name' => '三级分类3'],
                    ['id' => 14, 'name' => '三级分类4'],
                    ['id' => 15, 'name' => '三级分类5'],
                ],
            ],
        ];
    }

    /**
     * @param $result
     * @param $key
     * @param int $sort
     * @return array
     */
    public static function arrsSortByKey($result, $key, $sort = SORT_DESC) {
        if (!is_array($result) || !$key) {
            return [];
        }
        array_multisort(array_column($result, $key), $sort, $result);
        return $result;
    }
}